<!-- 组件说明 -->
<template>
  <div class='user'>
      <!-- 面包屑导航区域 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb> 
      <!-- 卡片视图 -->
      <el-card class="box-card">
        <!-- 搜索与添加区域 -->
        <el-row :gutter="20">
          <el-col :span="7">
            <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
              <el-button slot="append" @click="getUserList" icon="el-icon-search"></el-button>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
          </el-col>
        </el-row>
        <!-- 用户列表区域 -->
        <el-table :data="userList" border stripe >
          <el-table-column type="index" label="#"></el-table-column>
          <el-table-column label="姓名" prop="username"></el-table-column>
          <el-table-column label="邮箱" prop="email"></el-table-column>
          <el-table-column label="电话" prop="mobile"></el-table-column>
          <el-table-column label="角色" prop="role_name"></el-table-column>
          <el-table-column label="状态" prop="mg_state">
            <!-- 作用域插槽 -->
            <template slot-scope="scope">
              <el-switch @change="userStateChanged(scope.row)" v-model="scope.row.mg_state"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope" width="180px">
              <!-- 修改按钮 -->
              <el-button type="primary" @click="showEditDialog(scope.row.id)" size="mini" icon="el-icon-edit"></el-button>
              <!-- 删除按钮 -->
              <el-button type="danger" @click="deleteUser(scope.row.id)" size="mini" icon="el-icon-delete"></el-button>
              <!-- 分配角色按钮 -->
              <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
                <el-button type="warning" @click="showSetRolesDialog(scope.row)" size="mini" icon="el-icon-s-tools"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页功能 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" 
        :page-sizes="[1, 2, 5, 10]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
        <!-- 增加用户对话框 -->
        <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="45%" @close="addDialogClosed">
          <!-- 表单内容区域 -->
          <el-form :model="addUserForm" :rules="addUserRules" ref="addUserRuleForm" label-width="70px">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="addUserForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input type='password' v-model="addUserForm.password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="addUserForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
              <el-input v-model="addUserForm.mobile"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUser">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 修改用户信息对话框 -->
        <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="45%" @close="editDialogClosed">
          <!-- 内容区域 -->
          <el-form :model="editUserForm" :rules="addUserRules" ref="editUserRuleForm" label-width="70px">
            <el-form-item label="用户名" prop="username">
              <el-input disabled v-model="editUserForm.username"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="editUserForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
              <el-input v-model="editUserForm.mobile"></el-input>
            </el-form-item>
          </el-form>
          <!-- 底部区域 -->
          <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editUser">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 分配权限对话框 -->
        <el-dialog title="分配角色" :visible.sync="setRolesDialogVisible" width="45%" @close="setRolesDialogClosed">
          <!-- 内容区域 -->
          <div>
            <p>当前用户：{{userInfo.username}}</p>
            <p>当前角色：{{userInfo.role_name}}</p>
            <p>分配新的角色：
              <el-select v-model="selectedId" placeholder="请选择">
                <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName"
                  :value="item.id">
                </el-option>
              </el-select>
            </p>
          </div>
          <!-- 底部区域 -->
          <span slot="footer" class="dialog-footer">
            <el-button @click="setRolesDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="setRoles">确 定</el-button>
          </span>
        </el-dialog>
      </el-card>
  </div>
</template>

<script>
  //import x from ''
  export default {
    components: {

    },
    data () {
      // 校验规则
      var checkEmail = (rule,value,callback) => {
        const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])/
        if(regEmail.test(value)){
          return callback()
        }
        callback(new Error('请输入合法邮箱'))
      }
      var checkMobile = (rule,value,callback) => {
        const regMobile = /^(0|86|17951)?(13[0-9]|15[0-9]|17[678]|18[0-9]|14[5-7])[0-9]{8}$/
        if(regMobile.test(value)){
          return callback()
        }
        callback(new Error('请输入合法手机号码'))
      }
      return {
        //存储用户数据列表
        userList:[],
        //用户列表的参数对象
        queryInfo:{
          query:'',
          // 当前信息页数
          pagenum: 1,
          // 当前每页显示多少条数据
          pagesize: 2
        },
        total: 0,
        pagenum: 0,
        // 控制增加用户对话框显示与隐藏
        addDialogVisible:false,
        // 增加用户表单内容绑定
        addUserForm: {
         username:'',
         password:'',
         email:'',
         mobile:'',
        },
        //增加用户表单内容规则
        addUserRules: {
          username:[
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 10, message: '用户名的长度在3-10个长度之间', trigger: 'blur'}
          ],
          password:[
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 15, message: '密码的长度在6-15个长度之间', trigger: 'blur'}
          ],
          email:[
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            {validator:checkEmail, trigger: 'blur' }
          ],
          mobile:[
            { required: true, message: '请输入手机号', trigger: 'blur' },
            {validator:checkMobile, trigger: 'blur' }
          ]
        },
        // 控制修改用户对话框显示与隐藏
        editDialogVisible:false,
        // 查询到的用户信息
        editUserForm: {},
        //控制权限分配对话框显示与隐藏
        setRolesDialogVisible:false,
        //当前用户信息
        userInfo:{},
        //角色列表：
        rolesList:[],
        //创建角色中选中的角色ID
        selectedId: ''
      };
    },
    computed: {

    },
    created() {
      this.getUserList()
    }, 
    methods: {
      // 获取用户数据列表
      async getUserList(){
        const {data:res} = await this.$http.get('users',{params:this.queryInfo})
        if(res.meta.status !== 200) return this.$message.error('获取用户数据失败')
        this.userList = res.data.users
        this.total = res.data.total
        this.pagenum = res.data.pagenum
      },
        // 监听pagesize改变时间
      handleSizeChange(newsize){
        this.queryInfo.pagesize = newsize
        this.getUserList()
      },
      // 监听页码值改变的事件
      handleCurrentChange(newnum){
        this.queryInfo.pagenum = newnum
        this.getUserList()
      },
      //监听用户状态改变事件
      async userStateChanged(user){
        console.log('user',user);
        // 修改用户状态
        const {data:res} = await this.$http.put(`users/${user.id}/state/${user.mg_state}`)
        if(res.meta.status !== 200) {
          user.mg_state = !user.mg_state
          return this.$message.error(res.meta.msg)
        }
        console.log('res',res);
        this.$message.success('更新用户状态成功')
      },
      // 监听添加用户对话框的关闭事件
      addDialogClosed(){
        this.$refs.addUserRuleForm.resetFields()
      },
      //点击添加按钮
      addUser(){
        this.$refs.addUserRuleForm.validate(async valid => {
          console.log('valid',valid);
          if(!valid){
            return 
          }else{
            // 发出添加用户请求
            console.log();
            const {data:res} = await this.$http.post('users',this.addUserForm)
            if(res.meta.status !== 201) return this.$message.error('添加用户出错'+ res.meta.msg)
            this.$message.success("添加用户成功！")
            console.log('addUser',res.data);
            this.addDialogVisible = false
            //刷新列表
            this.getUserList()
          }
        })
      },
      // 监听修改用户对话框的关闭事件
      editDialogClosed(){
        this.$refs.editUserRuleForm.resetFields()
      },
      //显示修改用户信息对话框
      async showEditDialog(iid){
        this.editDialogVisible = true
        const {data:res} =  await this.$http.get(`users/`+ iid)
        if(res.meta.status !== 200) return this.$message.error("查询用户信息出错"+res.meta.msg)
        this.editUserForm = res.data
      },
      //修改用户信息
      editUser(){
        this.$refs.editUserRuleForm.validate(async valid => {
          if(!valid) return 
          const{data:res} = await this.$http.put(`users/${this.editUserForm.id}`,{email:this.editUserForm.email,mobile:this.editUserForm.mobile})
          if(res.meta.status !== 200) return this.$message.error("修改用户信息出错"+res.meta.msg)
          this.$message.success('修改用户信息成功！')
          this.getUserList()
          this.editDialogVisible = false
        })
      },
      // 删除用户信息
      async deleteUser(id){
        const res = await this.$confirm('确定删除该用户信息吗？, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if(res == 'confirm'){
          const{data:res} = await this.$http.delete('users/'+id)
          if(res.meta.status !== 200) return this.$message.error('删除失败')
          this.getUserList()
          this.$message.success("删除成功")
        }else{
          return this.$message.info("已取消删除")
        }
        
      },
      //监听分配角色对话框显示与隐藏
      async showSetRolesDialog(userInfo){
        this.setRolesDialogVisible = true
        this.userInfo = userInfo
        // 获取角色列表
        const{data: res} = await this.$http.get('roles')
        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.rolesList = res.data
      },
      //监听分配角色对话框关闭事件
      setRolesDialogClosed(){
        this.selectedId = ''
        this.userInfo = {}
        this.setRolesDialogVisible = false
      },
      //分配角色
      async setRoles(){
        const{data:res} = await this.$http.put(`users/${this.userInfo.id}/role`,{rid: this.selectedId})
        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success('分配角色成功！')
        this.getUserList()
        this.setRolesDialogVisible = false
      }
    },
    
  }
</script>

<style lang='less' scoped>

</style>